package com.steak.system.common.Aspect;

import com.auth0.jwt.JWT;
import com.steak.system.common.annotation.Permission;
import com.steak.system.common.exception.BusinessException;
import com.steak.system.common.exception.EmBusinessError;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
@Aspect
@Component
public class SecurityAspect {

    @Autowired
    private HttpServletRequest request;
    /**
     * 切入点
     */
    @Pointcut("@annotation(permission)")
    private void cutPermission(Permission permission){

    }

    @Around("cutPermission(permission)")
    public Object doPermission(ProceedingJoinPoint joinPoint, Permission permission) throws Throwable {
        String[] roles = permission.roles();
        if (roles.length == 0){
            return new BusinessException(EmBusinessError.NO_LOGIN);
        }else {
            String token = request.getHeader("TOKEN");
            String role = JWT.decode(token).getClaim("role").asString();
            for (String string : roles){
                if (string.equals(role)){
                    return joinPoint.proceed();
                }
            }
            throw new BusinessException(EmBusinessError.NO_AUTH);
        }
    }
}
